//
//  BSAddFanmilyViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/4/13.
//  Copyright © 2016年 Ym. All rights reserved.
//

#import "BSUIFamily.h"
#import "BSUIFamilyResponseList+Category.h"
#import "BSUIFamilyResponseList.h"
#import <FMDB.h>
#import "BSAddressBookViewController.h"
#import "BSAddAndDeleteCollectionViewCell.h"
#import "BSAddFamilyCollectionViewCell.h"
#import "BSAddFanmilyViewController.h"


@interface BSAddFanmilyViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,addPersonDelegate>
@property (nonatomic, strong) FMDatabase *db;
//  数据库的名字应该是和user_id绑定的
@property (nonatomic, strong) NSString *sqlName;

@property (nonatomic, strong) BSUIFamilyResponseList *listModel;
@property (nonatomic, strong) UICollectionView *collectionView;
@end

NSInteger numberOfperson;

@implementation BSAddFanmilyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:214.0/255 green:214.0/255 blue:214.0/255 alpha:1];

    [self getInformation];
    self.addView = [[BSAddFamiliesVuew alloc]initWithFrame:CGRectMake(0, 0, kScrenWidth, kScrenHeight - 0)];;
    [self.addView.backBT addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    [self.addView.saveBT addTarget:self action:@selector(save) forControlEvents:(UIControlEventTouchUpInside)];
    
    

    
    [self addCollectionView];

    [self.view addSubview:_addView] ;
    
    

}

- (void)addCollectionView{


    
    //    创建网状结构
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //    行间距
    layout.minimumLineSpacing = 1;
    //    列间距
    layout.minimumInteritemSpacing = 1;
    //    内边距
    //    整个分区的上下左右的缩近距离(内边距)
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0 );
    //    滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //    Item 大小
    layout.itemSize = CGSizeMake(kScrenWidth/3 -1, kScrenWidth/3 + 15);
    //    表头 表尾
    
   self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.addView.infoLB.bottom, kScrenWidth, kScrenHeight - self.addView.infoLB.bottom -(kScrenHeight - self.addView.saveBT.top)) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = self.view.backgroundColor;
    
    [_collectionView registerClass:[BSAddAndDeleteCollectionViewCell class] forCellWithReuseIdentifier:@"addCell"];
    [_collectionView registerClass:[BSAddFamilyCollectionViewCell class] forCellWithReuseIdentifier:@"famCell"];
    [self.addView addSubview:_collectionView];

}


//    创建UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return  1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _familyCount.count + 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 
    
    if (indexPath.row == _familyCount.count) {
        BSAddAndDeleteCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addCell" forIndexPath:indexPath];
        [cell.button setBackgroundImage:[UIImage imageNamed:@"sz_add_fmy.png"] forState:(UIControlStateNormal)];
        cell.backgroundColor = BSWhite;
        return cell;

    }else if (indexPath.row == _familyCount.count +1){
        BSAddAndDeleteCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addCell" forIndexPath:indexPath];
        [cell.button setBackgroundImage:[UIImage imageNamed:@"sz_del_norSel.png"] forState:(UIControlStateNormal)];
        cell.backgroundColor = BSWhite;
        
        return cell;
    
    }

    BSAddFamilyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"famCell" forIndexPath:indexPath];
    BSUIFamily *model = _familyCount[indexPath.row];
    cell.model = model;
    cell.iconImageView.image = [UIImage imageNamed:@"sz_addple_icon.png"];

    cell.tag = indexPath.row + 10;

    NSLog(@"cell的tag值,%ld",cell.tag);
    
    cell.deleteBT.hidden = YES;
    
    [cell.deleteBT addTarget:self action:@selector(deletePersonSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.backgroundColor = BSWhite;
    return cell;

    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == _familyCount.count) {
        NSLog(@"点击添加联系人");
        if (_familyCount.count >= 10) {
            [PKRequestManager showAlertView:@"最多添加10个联系人"];
            return;
        } else {
            
            BSAddAndDeleteCollectionViewCell *cell =(BSAddAndDeleteCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
            [cell.button setBackgroundImage:[UIImage imageNamed:@"sz_add_norSel.png"] forState:(UIControlStateNormal)];
    
            cell.backgroundColor = BSWhite;
            
            BSAddressBookViewController *addressVC = [[BSAddressBookViewController alloc]init];
            addressVC.addVC = self;
            //        设置代理 回来刷新界面
            addressVC.delegate = self;
            [self.navigationController pushViewController:addressVC animated:YES];

        }
    }
    if (indexPath.row == _familyCount.count + 1) {
        NSLog(@"删除某人");
        BSAddAndDeleteCollectionViewCell *cell = (BSAddAndDeleteCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
        [cell.button setBackgroundImage:[UIImage imageNamed:@"sz_deletFmy.png"] forState:(UIControlStateNormal)];
        
        [self deletePersonWithIndexPath:indexPath];
    }
    
  

}

- (void)back{

    [self.navigationController popViewControllerAnimated:YES];

}
- (void)save{
//    if (_isDeleting == YES) {
//           _isDeleting = NO;
//        for (int i = 10; i < _familyCount.count + 10; i++) {
//            BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell*)[self.collectionView viewWithTag:i ];
//            cell.deleteBT.hidden = YES;
//        }
//    } else {
        //            [self.collectionView reloadData];
        BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell *)[self.view viewWithTag:_familyCount.count + 9];
        NSLog(@"%ld",_familyCount.count + 9);
        cell.iconImageView.image = [UIImage imageNamed:@"sz_addple_icon.png"];
        
        
        [self.collectionView reloadData];
//    }

}


// 实现代理的方法
- (void)passPerson:(BSUIFamily *)model{

    BOOL isContain = NO;
    for (int i = 0; i < _familyCount.count; i++) {
        
        BSUIFamily *fmodel = _familyCount[i];
        if ((fmodel.ID == model.ID)&&[model.LoginName isEqualToString:fmodel.LoginName]) {
            isContain = YES;
        }
            }
    if (isContain == NO) {
        if (self.familyCount.count < 12) {
             [self.familyCount addObject:model];
//                [self.collectionView reloadData];
            NSIndexPath *index = [NSIndexPath indexPathForRow:self.familyCount.count -1 inSection:0];

            [self.collectionView insertItemsAtIndexPaths:@[index]];
            
            
            //            [self.collectionView reloadData];
            BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell *)[self.view viewWithTag:_familyCount.count + 9];
            NSLog(@"%ld",_familyCount.count + 9);
            cell.iconImageView.image = [UIImage imageNamed:@"sz_addple_icon2.png"];
            
            return;
        }

    } else {
        [PKRequestManager showAlertView:@"已经添加过此人"];
    }
    
   //    插入紧急联系人
//    [_db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@ (name, phoneNumber) VALUES (?,?)",_sqlName],model.name,model.phones[0]];
}
// 找到紧急联系人
- (void)getPersonList{

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:_sqlName];
    
    FMDatabase  *db = [FMDatabase databaseWithPath:path];
    
    [db open];
//    NSString *sql = @"select * from lanOuStudent where name = ? and age = ?";

//    @"SELECT name , phonenumber FROM PersonList "
    FMResultSet *rs =  [db executeQuery:[NSString stringWithFormat:@"SELECT name , phonenumber FROM %@ ",_sqlName]];
    while ([rs next]) {
        ContactModel *model = [[ContactModel alloc]init];
        model.name = [rs stringForColumn:@"Name"];
        model.phones = [NSMutableArray array];
        model.phones[0] = [rs stringForColumn:@"phoneNumber"];
        [self.personCount addObject:model];
    }
    [rs close];
}

// 创建数据库 保存要使用的联系人
- (void)creatPersonList{

    //  创建我们的数据库的路径 同时拼接数据库的文件名称
    self.sqlName = [NSString stringWithFormat:@"%@%@",_user_id,@"List.db"];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:_sqlName];
    
//    NSLog(@"数据库表的位置 >> %@",path);
    
    //  根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    //    NSLog(@"%@",path);
    
    //  调用open方法 打开成功返回YES 失败 返回NO
    if ([_db open]) {
        NSLog(@"数据库打开成功");
    }else
    {
        NSLog(@"数据库打开失败");
    }
    //  调用db的executeUpdata 这个方法的参数就是SQL 语句
//    @"CREATE TABLE PersonList (name text, phoneNumber text)"
    [_db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE %@ (name text, phoneNumber text)",_sqlName]];
}

// 删除联系人
- (void)deletePersonWithIndexPath:(NSIndexPath *)indexpath{
    _isDeleting = NO;

//    for (int i = 10; i < _familyCount.count + 10; i++) {
//        BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell*)[self.collectionView viewWithTag:i ];
//        cell.deleteBT.hidden = NO;
//    }
        for (int i = 0; i < _familyCount.count ; i++) {
            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];

            BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell *)[_collectionView cellForItemAtIndexPath:index];
            cell.deleteBT.hidden = NO;
        }
}
- (void)deletePersonSelect:(UIButton *)button{
    
    if (_isDeleting == NO) {
        _isDeleting = YES;
        BSAddFamilyCollectionViewCell *cell = (BSAddFamilyCollectionViewCell*)button.superview.superview;
        BSUIFamily *model = cell.model;
        
        // 提交删除申请
        self.user_id = [BSUserSGton userHandle].user_id;
        [PKRequestManager DeleteUserFamilyWithnetUrl:NetStr userID:self.user_id iD:model.ID method:POST finish:^(NSData *data) {
            
            if ([self.familyCount containsObject:model]) {
                [self.familyCount removeObject:model];
            }
            NSIndexPath *index = [NSIndexPath indexPathForRow:cell.tag - 10 inSection:0];
            NSLog(@"%ld",index.row);
            [_collectionView deleteItemsAtIndexPaths:@[index]];
            
        } error:^(NSError *error) {
            [PKRequestManager showAlertView:@"提交服务器失败"];
        }];
    } else {
        [PKRequestManager showAlertView:@"请先保存"];
    }
}


//进来之前 先获取 之前已经添加的家属
- (void)getInformation{

    NSString *user_id = [BSUserSGton userHandle].user_id;
    [PKRequestManager GetMyFamilyWithnetUrl:NetStr userID:user_id method:POST finish:^(NSData *data) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        _listModel = [[BSUIFamilyResponseList alloc]init];
        [_listModel dealWithData:data];
        ;
        self.familyCount = self.listModel.pArr;
        [self addCollectionView];
    } error:^(NSError *error) {
        ;
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    
    //    创建保存家人的列表
    dispatch_async(dispatch_get_main_queue(), ^{
        //        [self creatPersonList];
    }) ;
}
- (NSMutableArray *)familyCount{

    if (!_familyCount) {
        _familyCount = [[NSMutableArray alloc]init];
    }
    return _familyCount;
}
- (NSMutableArray *)personCount{
    
    if (!_personCount) {
        _personCount = [[NSMutableArray alloc]init];
    }
    return _personCount;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
